package com.leo.mybatis;

import com.leo.mybatis.mapper.StudentMapper;
import com.leo.mybatis.pojo.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

public class TkMapperTest {

    private StudentMapper studentMapper;
    private SqlSession sqlSession;

    @Before
    public void before() throws IOException {

        //使用InputStream或者Reader都可以
        //InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        Reader reader = Resources.getResourceAsReader("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        //开启事务自动提交
        sqlSession = sqlSessionFactory.openSession(true);
        studentMapper = sqlSession.getMapper(StudentMapper.class);
    }

    @After
    public void after(){
        sqlSession.close();
    }

    /**
     * insert             null值会被保存
     * insertSelective    null值不会被保存
     */
    @Test
    public void insert(){
        Student param = new Student();
        param.setUsername("duyu");
        studentMapper./*insert*/insertSelective(param);
    }

    @Test
    public void update(){
        Student param = new Student();
        param.setId(1);
        param.setUsername("leo");
        studentMapper.updateByPrimaryKey(param);
    }

    @Test
    public void select(){
        Student param = new Student();
        param.setId(1);
        param.setUsername("leo");
        Student student = studentMapper.selectOne(param); //
        System.out.println(student);
        List<Student> list = studentMapper.select(null); //
        Student student1 = studentMapper.selectByPrimaryKey(1);//
        int count = studentMapper.selectCount(param);
        System.out.println(count);
    }

    @Test
    public void delete(){
        //int delete = userMapper.delete(user);
        studentMapper.deleteByPrimaryKey(1);
    }

    /**
     * 自定义条件查询
     */
    @Test
    public void example(){
        Example example = new Example(Student.class);
        example.createCriteria().andEqualTo("id", 1);

        List<Student> students = studentMapper.selectByExample(example);
        System.out.println(students);
    }
}
